package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-15 9:31
 */
@Service
@Slf4j //注解在lombok自动生成日志对象
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WmMaterial upload(MultipartFile multipartFile) {

        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            //用户未登录
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        String path = null;
        //1.将文件上传到MinIO
        //处理文件名
        try {
            String fileName = UUID.randomUUID().toString();
            String originalFilename = multipartFile.getOriginalFilename(); //a.jpg -> UUID.jpg a

            int i = originalFilename.lastIndexOf(".");
            if (i != -1) {
                fileName = fileName + originalFilename.substring(i);
            }

            path = fileStorageService.uploadImgFile(null, fileName, multipartFile.getInputStream());
        } catch (Exception e) {
            //打印日志
            log.error("上传图片-上传文件异常!", e);
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }

        //2.数据保存数据库
        try {
            WmMaterial wmMaterial = new WmMaterial();
//            wmMaterial.setType((short) 0);
//            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setUrl(path);
            wmMaterial.setUserId(user.getId());
            wmMaterial.setCreatedTime(new Date());
            save(wmMaterial);

            //3.返回结果
            return wmMaterial;
        } catch (Exception e) {
            //打印日志
            log.error("上传图片-保存数据库异常!", e);
            //删除图片
            fileStorageService.delete(path);
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }


    }

    @Override
    public ResponseResult findMaterialList(WmMaterialDto dto) {
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            //用户未登录
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //查询
        Page<WmMaterial> page = new Page<>();
        page.setSize(dto.getSize());
        page.setCurrent(dto.getPage());

        //处理收藏 1收藏的 0全部
        LambdaQueryWrapper<WmMaterial> wrappers = Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getUserId, user.getId())
                .eq(dto.getIsCollection() != null && dto.getIsCollection() == 1,WmMaterial::getIsCollection,1)
                .orderByDesc(WmMaterial::getCreatedTime);



        Page<WmMaterial> pageResult = page(page, wrappers);

        PageResponseResult result = new PageResponseResult((int) pageResult.getCurrent(),
                (int) pageResult.getSize(), (int) pageResult.getTotal());

        result.setData(pageResult.getRecords());

        return result;
    }
}
